package com.qf.servlet;

import com.qf.constant.MessageConstant;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author AzureSky_X
 * @Date 2021/1/13 15:05
 * @Version 1.0
 * 修改用户信息
 */
@WebServlet("/updateUser")
public class UpdateUserController extends HttpServlet {
    UserService userService=new UserServiceImpl();
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String errorMessage = "";

        try{
            //将String格式的id转化成int格式
            Integer id=Integer.valueOf(request.getParameter("id"));

            //Object bean, Map properties
            //bean : 组件，模型，Java实体
            //Map : 数据
            //如果map中有key跟Java实体的属性是一致的，那么，就可以使用如下API进行封装
            //把 map中的数据 封装 Java实体中
            Map<String, String[]> parameterMap = request.getParameterMap();
            User user = new User();
            user.setId(id);
            // 把 map中数据放到 employee对象中
            BeanUtils.populate(user, parameterMap);


//            String idStr = request.getParameter("id");
//            Integer id = Integer.valueOf(idStr);


            System.out.println(user);

            //调用业务层，完成修改功能
            userService.updateUser(user);

            //选择重定向
            response.sendRedirect(request.getContextPath() + "/user/list");
            return;
        } catch (NumberFormatException e){
            errorMessage = "不要乱传ID,ID必须是整形的";
        } catch (RuntimeException e) {
            e.printStackTrace();
            errorMessage = MessageConstant.DB_ERROR;
        } catch (Exception e) {
            errorMessage = MessageConstant.COMMON_ERROR;
        }

        response.getWriter().write("<script>alert('" + errorMessage + "');</script>");


    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}